package cn.pconline.autoclub.service;

import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.DynaImage;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.dyna.CommentDyna;
import cn.pconline.officialclub.service.ODynaService;
import cn.pconline.passport2.util.T;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * 审核服务类
 */
public class CensorDynaInfoService extends CensorService {

    // 留言typeId,在bean初始化的时候赋值
    private long typeIdDynaInfo;
    @Autowired
    private ClubService clubService;
    @Autowired
    private DynaService dynaService;
    @Autowired
    private ODynaService oDynaService;
    @Autowired
    private UserService userService;
    @Autowired
    private CensorCommentService censorCommentService;

    public void setTypeIdDynaInfo(long typeIdDynaInfo) {
        this.typeIdDynaInfo = typeIdDynaInfo;
    }

    /**
     * 审核应用回馈
     *
     * @param interfaceUrl
     * @param url
     * @param status
     * @param version
     * @return
     */
    public String feedback(String interfaceUrl, String url, int status, long version) {

        String result = null;
        // url must format like : http://club.pcauto.com.cn/gzkpq/dt/56417/?typeId=272&clubId=2546&dynaInfoId=56417&createDate=2014
        // url must format like : http://club.pcauto.com.cn/gzqrcyh/comment/?typeId=272&clubId=200&commentId=300
        //因为以前发留言跟现在发动态的审核用的是同一个typeId
        Map<String, Long> map = getMapByUrl(url);
        //为空时为留言交给留言处理
        if (map.get("dynaInfoId") == null) {
            result = censorCommentService.feedback(interfaceUrl, url, status, version);
            return result;
        }
        long id = map.get("dynaInfoId");
        long typeId = map.get("typeId");
        Long oClubId = map.get("oClubId");
        if (oClubId == null) {
            oClubId = 0L;
        }
        if (typeId == typeIdDynaInfo) {
            DynaInfo dynaInfo = null;
            Long create = map.get("createDate");
            if (create != null) {
                Date createDate = DateUtils.createDate(create.intValue());
                dynaInfo = dynaService.findDynaInfoById(id, createDate);
            }
            if (dynaInfo == null) {
                log.info("审核平台回调留言已不存在:" + id);
                return "审核平台回调留言已不存在";
            }
            if (version == dynaInfo.getUpdateAt().getTime()) {
                switch (status) {
                    //审核通过?
                    case CENSORSYSTEM_RESPONSE_PASS:
                        dynaService.censorDynaInfo(dynaInfo, DynaInfo.CENSORED_PASS);
                        if (oClubId > 0) {
                            oDynaService.censorDynaInfo(dynaInfo, oClubId, DynaInfo.CENSORED_PASS);
                        }
                        break;
                    //审核不通过    
                    case CENSORSYSTEM_RESPONSE_DENY:
                        dynaService.censorDynaInfo(dynaInfo, DynaInfo.CENSORED_NOTPASS);
                        if (oClubId > 0) {
                            oDynaService.censorDynaInfo(dynaInfo, oClubId, DynaInfo.CENSORED_NOTPASS);
                        }
                        break;
                    default:
                        result = "状态不正确";
                        break;
                }
            }
        }
        return result;
    }

    /**
     * 发留言时,首次通知审核平台新建留言状态
     *
     * @param request
     * @param comment
     */
    public void notifyCensorSystemCreate(HttpServletRequest request, final CommentDyna commentDyna,
            long dynaInfoId) {
        notifyCensorSystemCreate(request, commentDyna, dynaInfoId, 0);
    }

    /**
     * 发留言时,首次通知审核平台新建留言状态
     *
     * @param request
     * @param comment
     */
    public void notifyCensorSystemCreate(HttpServletRequest request, final CommentDyna commentDyna,
            long dynaInfoId, long oClubId) {
        if (csr_switch) {
            DynaInfo dynaInfo = new DynaInfo();
            dynaInfo.setDynaInfoId(dynaInfoId);
            dynaInfo.setClubId(commentDyna.getClubId());
            dynaInfo.setContent(commentDyna.getContent());
            dynaInfo.setCreateBy(commentDyna.getCreateBy());
            dynaInfo.setCreateAt(commentDyna.getCreateDate());
            dynaInfo.setCreateName(commentDyna.getCreateName());
            dynaInfo.setUpdateAt(commentDyna.getUpdateDate());
            final Map<String, Object> params = convert4Create(request, dynaInfo, oClubId, true);
            executorService.submit(new CensorCall(receiveHome, params));
        }
    }

    /**
     * 将CommentDyna类转换成向审核系统传递的参数,只用在新建动态时
     *
     * @param userProfile
     * @param isNew
     * @return
     */
    private Map<String, Object> convert4Create(HttpServletRequest request, DynaInfo dynaInfo, long oClubId, boolean isNew) {
        Club club = clubService.getClub(dynaInfo.getClubId());
        User user = userService.findUser(dynaInfo.getCreateBy());
        Map<String, Object> map = new HashMap<String, Object>(16);
        if (user == null) {
            log.error("Censor DynaInfo Error! user[{}] not exist!", dynaInfo.getCreateBy());
            return map;
        }
        if (club == null) {
            log.error("Censor DynaInfo Error! club[{}] not exist!", dynaInfo.getClubId());
            return map;
        }
        //标题
        map.put(TITLE, dynaInfo.getContent());
        map.put(SITE, site);
        map.put("isHtml", 1);
        map.put(APP, appName);
        map.put(TYPEID, typeIdDynaInfo);
        map.put(ISNEW, isNew ? 1 : 0);
        String root = "http://" + T.stringValue(request.getHeader("host"), "") + T.stringValue(request.getContextPath(), "");
        map.put(URI, root + "/dyna/getDynaInfoDetail.do?createDate=" + DateUtils.format(dynaInfo.getCreateAt(), "yyyy") + "&typeId="
                + typeIdDynaInfo + "&dynaInfoId=" + dynaInfo.getDynaInfoId());
        map.put(VERSION, (dynaInfo.getUpdateAt().getTime() / 1000) * 1000);
        map.put(USERID, user.getUid());
        map.put(USERNAME, user.getUsername());
        map.put(IP, T.getIp(request));
        map.put(CONTENT, convert2DynaContent(dynaInfo));
        if (oClubId > 0) {
            map.put("oClubId", oClubId);
        }
        return map;
    }
    
    /**
     * 生成送审内容（包括图片）
     * @param dynaInfo
     * @return
     */
    private String convert2DynaContent(DynaInfo dynaInfo){
    	String content = dynaInfo.getContent();
    	List<DynaImage> images = dynaService.getImagesByDynaInfoId(dynaInfo.getDynaInfoId(),0);
    	if(images.isEmpty()) return content;
    	StringBuffer stringBuffer = new StringBuffer();
    	stringBuffer.append("<ul>");
    	for(DynaImage image : images){
    		String url = image.getUrl();
    		if(!StringUtils.isBlank( url )){
    			stringBuffer.append("<img src='"+url+"'></img>");
    		}
    	}
    	stringBuffer.append("</ul>");
    	content += stringBuffer.toString();
    	return content;
    }

    @Override
    public boolean isCorrectFeedback(String url) {
        Map<String, Long> map = getMapByUrl(url);
        long typeId = 0;
        if (map != null && !map.isEmpty()) {
            typeId = map.get("typeId");
        }
        return typeIdDynaInfo == typeId;
    }
}
